var TCPTransceiver  =  function() {
    this._adapter    =   undefined;
    this._socket     =   undefined;
    this._stream     =   undefined;
    this._netthread  =   undefined;
    this._uid        =   0;
    this._socket_evt =   undefined;
    this._iTimeout   =   60000;
}

module.exports.TCPTransceiver = TCPTransceiver;

TCPTransceiver.prototype.initialize = function() {
    var self  = this;

    self._socket_evt = {
        close   :   function()          { self.close(); },
        error   :   function()          { self.close(); },
        timeout :   function()          { self.close(); },
        data    :   function(data)      { self._stream.feed(data); },
        message :   function(request)   { self._adapter.dispatch(self, request); }
    };

    self._socket.on("data",     self._socket_evt.data);
    self._socket.on("error",    self._socket_evt.error);
    self._socket.on("close",    self._socket_evt.close);
    self._socket.on("timeout",  self._socket_evt.timeout);
    self._stream.on("message",  self._socket_evt.message);

    self._socket.setTimeout(this._iTimeout);
}

TCPTransceiver.prototype.close  =   function() {
    if(this._socket) {
        try{
            this._netthread.remove(this._uid);

            this._socket.removeListener("error",    this._socket_evt.error);
            this._socket.removeListener("close",    this._socket_evt.close);
            this._socket.removeListener("data",     this._socket_evt.data);
            this._socket.removeListener("timeout",  this._socket_evt.timeout);

            this._stream.removeListener("message",  this._socket_evt.message);

            this._socket.destroy();

            this._socket = undefined;
        }catch(e) {
            console.error('[TCPTransceiver.close]' + e.message);
        }
    }
}

TCPTransceiver.prototype.send   =   function(request) {
    if(this._socket)
        this._socket.write(this._stream.compose(request));
}

TCPTransceiver.prototype.setTimeout =   function(iTimeout) {
    this._iTimeout = iTimeout;
}


var UDPTransceiver  =   function() {
    this._adapter   = undefined;
    this._socket    = undefined;
    this._stream    = undefined;
    this._endpoint  = undefined;

    this._iTimeout  = 60000;
}

module.exports.UDPTransceiver = UDPTransceiver;

UDPTransceiver.prototype.doRequest  = function(request) {
    var self = this;
    self._stream.reset();
    self._stream.on("message", function(request) { self._adapter.dispatch(self, request); });
    self._stream.feed(request);
}

UDPTransceiver.prototype.send   =   function(request) {
    var buffer = this._stream.compose(request);
    this._socket.send(buffer, 0, buffer.length, this._endpoint.iPort, this._endpoint.sHost);
}

UDPTransceiver.prototype.setTimeout = function(iTimeout) {
    this._iTimeout = iTimeout;
}

UDPTransceiver.prototype.close  = function() {
    console.log("[UDPTransceiver.close]");
}